package com.example.code.rsa;

import org.springframework.util.Base64Utils;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAT {


    public static void main(String[] args) {
        KeyPair keyPair = generateRSAKeyPair(512);

        System.out.println(keyPair);
    }
    /**
     * 生成RSA密钥对
     *
     * @param keyLength 密钥长度，范围：512～2048
     * @author wenfengzhuo
     */
    public static KeyPair generateRSAKeyPair(int keyLength) {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * 将私钥转化为xml格式
     *
     * @param encodedPrivkey=privateKey.getEncoded()
     *
     * @author wenfengzhuo
     */
    private static String  privatekeyinfoToXMLRSAPriKey(byte[] encodedPrivkey) {
        try{
            StringBuffer buff = new StringBuffer(1024);

            PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(encodedPrivkey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey)keyFactory.generatePrivate(pvkKeySpec);

            buff.append("<RSAKeyValue>") ;
            buff.append("<Modulus>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getModulus().toByteArray())) + "</Modulus>");

            buff.append("<Exponent>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getPublicExponent().toByteArray())) + "</Exponent>");

            buff.append("<P>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getPrimeP().toByteArray())) + "</P>");

            buff.append("<Q>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getPrimeQ().toByteArray())) + "</Q>");

            buff.append("<DP>" +Base64Utils.encodeToString(removeMSZero(pvkKey.getPrimeExponentP().toByteArray())) + "</DP>");

            buff.append("<DQ>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getPrimeExponentQ().toByteArray())) + "</DQ>");

            buff.append("<InverseQ>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getCrtCoefficient().toByteArray())) + "</InverseQ>");

            buff.append("<D>" + Base64Utils.encodeToString(removeMSZero(pvkKey.getPrivateExponent().toByteArray())) + "</D>");
            buff.append("</RSAKeyValue>") ;

            return buff.toString();
        }
        catch(Exception e)
        {System.err.println(e);
            return null ;
        }
    }


    /**
     * 实现java和C# key的byte[]值互通
     *
     * @author wenfengzhuo
     */
    private static byte[] removeMSZero(byte[] data) {
        byte[] data1 ;
        int len = data.length;
        if (data[0] == 0)
        {
            data1 = new byte[data.length-1] ;
            System.arraycopy(data, 1, data1, 0, len-1);
        }
        else
            data1 = data;

        return data1;
    }
}
